<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			ul{
				list-style: none;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="input-box">

			</div>
			<div class="out-box">
				<ul id="jsontree">

				</ul>
			</div>
		</div>
	</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
	var source =
		`{"sites":{"site":[{"id":"1","name":"菜鸟教程","url":"www.runoob.com","school":{"address":"苏州市苏州","level":10}},{"id":"2","name":"菜鸟工具","url":"c.runoob.com"},{"id":"3","name":"Google","url":"www.google.com"}]}}`;
	var jsonObject = JSON.parse(source);
	var outTree = document.getElementById("jsontree");
	var out = "";

	function format(json, context) {
		//数组
		if (json instanceof Array) {
			let arrayFirstToken = document.createElement("li");
			arrayFirstToken.innerHTML="\"[\"";
			context.append(arrayFirstToken)
			for (var i = 0; i < json.length; i++) {
				let element = json[i];
				_renderArray(context, element)
			}
			let arrayEndToken = document.createElement("li");
			arrayEndToken.innerText="\"]\"";
			context.append(arrayEndToken)
		} else if (typeof(json) == "object") {
			for (let key in json) {
				let node = document.createElement("li");
				context.appendChild(node);
				let element = json[key];
				if (element == null) {
					node.innerText = "\"" + key + "\":null";
				} else if (typeof(element) == "object") {
					let ul = document.createElement("ul");
					let p = document.createElement("span");
					p.innerText=key;
					node.appendChild(p);
					node.appendChild(ul);
					format(element, ul);
				} else if (typeof(element) == "string") {
					node.innerText = "\"" + key + "\" : \"" + element + "\"";
				} else {
					node.innerText = element;
				}
			}
		}
	}

	function _renderArray(p, value) {
		let li = document.createElement("li");
		p.appendChild(li);
		if (typeof(value) == "object") {
			let ul = document.createElement("ul");
			li.appendChild(ul);
			format(value, ul);
		} else if (typeof(value) == "string") {
			li.innerText = "\"" + value + "\"";
		} else {
			li.innerText = value;
		}
	}

	format(JSON.parse(source), outTree);
</script>
